/**
 *	Monster Class
 *	By D5Power Studio
 *	This is not extend from dotk
 */
var monster_fight_target=null;		//	记录战斗对象，直到战斗全部结束（用于删除对象）
var rival=null;						//	记录战斗对象，直到战斗结束（用于战斗过程判断）
var monster_fight_Turn = null;		//	回合记录
var fightBox=null;					//	战死一方的容器
var walk_to_monster = null;			//	移动到怪身边时的目标

 
Monster = Class.create();
Monster.prototype = {
		initialize:function(p,monsterId,name,actualPosition,avatar,_str,_dex,_agi,_int,_vit,_level,_atk,_def)
		{
			// There p is for defferent monster
			this.p = p;
			this.monsterId = monsterId;
			this.name = name;
			this.actualPosition = actualPosition;
			this.avatar = avatar;
			this.busy = false;
			
			this.str = _str;
			this.dex = _dex;
			this.agi = _agi;
			this.int = _int;
			this.vit = _vit;
			this.lv = _level;
			this.atk = _atk;
			this.def = _def;
			
			this.hp = this.getMonstersHp();
			
			this.walking = false;
			this.pointsToWalk = [];
			this.speed = 2;
			this.lookingTo = 'left';
			
			this.charWidth = 48;
			this.charHeight = 48;
			
			//Configuring character container (div)
			this.charContainer = document.createElement('DIV');
			this.charContainer.id = 'Monster_'+this.monsterId+'_'+this.p;
			this.charContainer.setAttribute('monsterId',this.p)
			this.charContainer.className = 'monster';
			this.charContainer.innerHTML = "<img src = \"..\/pictures\/monster\/"+ this.avatar +"_"+this.lookingTo+".gif\">";
			$('characters_layer').appendChild(this.charContainer);
			
			//Configuring character's name container (div)
			/*
			this.charLabelContainer = document.createElement('DIV');
			this.charLabelContainer.id = "monster"+this.monsterId+'Label';
			this.charLabelContainer.className = 'monsterLabel';
			this.charLabelContainer.innerHTML = '<div style="position: absolute; top: 1px; left: 1px; color: #000;">'+ this.name + '</div>';
			this.charLabelContainer.innerHTML += '<div style="position: absolute; top: 0px; left: 0px;color:#FF9900">'+ this.name + '</div>';
			$('up_layer').appendChild(this.charLabelContainer);
			*/
			//Configuring character container (div)
			this.charEventDiv = document.createElement('DIV');
			this.charEventDiv.id = this.monsterId+'_'+this.p;
			this.charEventDiv.name = this.name;
			this.charEventDiv.avatar = this.avatar;
			this.charEventDiv.className = 'monster';
			if(document.addEventListener)
			{
				this.charEventDiv.addEventListener('click',gotoCloseMonster,true);
			}else{
				this.charEventDiv.attachEvent('onclick',gotoCloseMonster);
			}
			$('events_layer').appendChild(this.charEventDiv);
			
			this.moveLayers(this.actualPosition.x,this.actualPosition.y);
		},
		
		moveLayers: function(newPoint_x, newPoint_y)
		{
			this.charContainer.style.left = (newPoint_x - this.charWidth/2)+"px";
			this.charContainer.style.top = (newPoint_y - this.charHeight)+"px";
			this.charEventDiv.style.left = (newPoint_x - this.charWidth/2)+"px";
			this.charEventDiv.style.top = (newPoint_y - this.charHeight)+"px";
			//this.charLabelContainer.style.left = (newPoint_x-20)+"px";
			//this.charLabelContainer.style.top = (newPoint_y+2)+"px";
			return;
    	},
		
		changePicture: function() {
			this.charContainer.innerHTML = "<img src = \"..\/pictures\/monster\/"+ this.avatar +"_"+this.lookingTo+".gif\">";
		},
		
		destroy: function()
		{
			$('characters_layer').removeChild(this.charContainer);
			//$('up_layer').removeChild(this.charLabelContainer);
			$('events_layer').removeChild(this.charEventDiv);
			return;
    	},
		getMonstersHp:function()
		{
			hp = Math.floor(this.lv*this.lv*this.vit/6+40);
			return hp;
		},
		
		walk : function() {
			if(this.walking) {
				if(this.busy)
				{
					this.walking = false;
					return;
				}
				var alreadyLooking = false;
				var target = tileToPixel(this.pointsToWalk[0]);
				if(target.x == this.actualPosition.x && target.y == this.actualPosition.y) {
					this.pointsToWalk.shift();
					if(this.pointsToWalk.length == 0) {
						this.walking = false;
						return;
					}
				}
				target = tileToPixel(this.pointsToWalk[0]);
				
				if(target.x > this.actualPosition.x) { 
					this.actualPosition.x += this.speed; 
					if(this.lookingTo!='right')
					{
						this.lookingTo = 'right';
						this.changePicture();
					}
					alreadyLooking = true;
				}
				else if(target.x < this.actualPosition.x) {
					this.actualPosition.x -= this.speed;
					if(this.lookingTo!='left')
					{
						this.lookingTo = 'left';
						this.changePicture();
					}
					alreadyLooking = true;
				}
				
				if(target.y > this.actualPosition.y) { 
					this.actualPosition.y += this.speed;
				}
				else if(target.y < this.actualPosition.y) { 
					this.actualPosition.y -= this.speed; 
				}
				this.moveLayers(this.actualPosition.x, this.actualPosition.y);
			}
		}
		
		
};

/**
 * monster List Class
 * Structure to handle character instances.
 */
monsterList = Class.create();
monsterList.prototype = {
  initialize: function() {
    this.list = [];
	this.monsterInfo=null; // 怪物数量，用于统计怪物重生
  },
  setMonsterInfo: function(info) {
	  this.monsterInfo = info;
  },
  add: function(monsterInstance) {
    this.list.push(monsterInstance);
    return;
  },
  
  length: function() {
    return this.list.length;
  },

  remove: function(monster) {
    for (i=0; i<this.list.length; i++) {
      if (this.list[i].monsterId == monster.monsterId && this.list[i].p == monster.p) {
        this.list[i].destroy();
        this.list[i] = null;
      }
    }
    this.list = this.list.compact();	
    return;
  },

  getById: function(monsterId) {
    for (i=0; i<this.list.length; i++) {
      if (this.list[i].monsterId == monsterId) {
        return this.list[i];
      }
    }
    return null;
  },
  
  getByPersonId:function(monsterId,p){
	for (i=0; i<this.list.length; i++) {
      if (this.list[i].monsterId == monsterId && this.list[i].p==p) {
        return this.list[i];
      }
    }
    return null;
  },

  getByIndex: function(index) {
    return this.list[index];
  }
  
};

function monsterBirth(serverInfo)
{
	if(serverInfo!=undefined)
	{
		monstersOnScreen.setMonsterInfo(serverInfo);
	}else{
		if(monstersOnScreen.monsterInfo==null) return;
	}
	monstersOnScreen.list = [];
	monster_data = monstersOnScreen.monsterInfo;
	for(var i=0;i<monster_data[0]._num;i++)
	{
		monstersOnScreen.add(arrayToMonster(monster_data[0],i));
	}
}
	function gotoCloseMonster(event)
	{
		if(event.srcElement)
		{
			var target = event.srcElement;
		}else{
			var target = event.target;
		}
		// 事件对象的ID是怪物的ID加上_加上其屏幕编号p
		temp = target.id.split('_');
		walk_to_monster = monstersOnScreen.getByPersonId(temp[0],temp[1]);
		
		// 让目标静止不动
		walk_to_monster.busy = true;
		// 判断开始战斗的代码见engine.js Character walk方法
	}
	
	function fightWithMonster()
	{
		monster_fight_target = walk_to_monster;
		walk_to_monster = null;
		rival = monster_fight_target; //定义敌人
		showMonsterBattleScreen();
	}
	
	function hiddenMonsterBattleScreen()
	{
		$('battle_screen').style.display='none';
		if(fightBox=='rival')
		{
			monstersOnScreen.remove(monster_fight_target);
			// 判断目前的怪物数量
			if(monstersOnScreen.length()==0) monsterBirth();
		}
		$(fightBox).style.display='';
		fightBox=null;
		monster_fight_target=null;
		rival=null;
		monster_fight_Turn = null;
		setChatWindow();
	}
	function showMonsterBattleScreen()
	{
		if(monster_fight_target==null)
		{
			return false;
		}
		
		var battle_screen = $('battle_screen');
		try
		{
			$(fightBox).style.display='block';
		}catch(e){
		
		}
		//if(!battle_screen.style.display == 'block') {
		$('portrait').innerHTML = '<img style="width: 48px; height: 48px;" alt="" src="../pictures/chipsets/'+myCharacter.pictureKind+'.gif">';
		$('my_name').innerHTML = myCharacter.name;
		$('my_hp').innerHTML = myCharacter.hp;
		
		
		$('rival_portrait').innerHTML = '<img style="width: 48px; height: 48px;" alt="" src="../pictures/monster/'+rival.avatar+'_left.gif">';
		
		$('rival_name').innerHTML = rival.name;
		
		$('rival_hp').innerHTML = rival.hp;
		
		battle_screen.style.display = 'block';
		//}
		showMonsterFightMessage('');
		setChatWindow();
		startMonsterFight();
		return;
	}
	
	function startMonsterFight()
	{
		monster_fight_Turn = monster_fight_Turn==null ? fightMonsterDefineTurn() : monster_fight_Turn;
		if(monster_fight_Turn=='ME')
		{
			$('action_atacar').innerHTML = '<img style="width: 32px; height: 32px;" alt="" src="../pictures/fight/attack.jpg" onClick="fightMonsterAttack();">';
			$('action_defender').innerHTML = '<img style="width: 32px; height: 32px;" alt="" src="../pictures/fight/defend.jpg" onClick="fightMonsterDefend();">';
		}else{
			$('action_atacar').innerHTML = '<img style="width: 32px; height: 32px;" alt="" src="../pictures/fight/attack_pb.jpg">';
			$('action_defender').innerHTML = '<img style="width: 32px; height: 32px;" alt="" src="../pictures/fight/defend_pb.jpg">';
			setTimeout('fightMonsterBeAttacked()',2000);
		}
	}

	function fightMonsterAttack()
	{
		if(rival==null) return;
		if(monster_fight_Turn!='ME') return;
		var fdata = fightMonsterFight(myCharacter,rival);
		showMonsterFightMessage(fdata,monster_fight_Turn);
		if(rival==null) return;
		startMonsterFight();
	}
	
	function fightMonsterBeAttacked()
	{
		if(rival==null) return;
		var fdata = fightMonsterFight(rival,myCharacter);
		showMonsterFightMessage(fdata,monster_fight_Turn);
		if(rival==null) return;
		startMonsterFight();
	}

	function showMonsterFightMessage(data,type)
	{
		if(rival==null) return;
		if(data==undefined) return;
		if(data=='')
		{
			$('battle_history').innerHTML='';
			return;
		}
		
		if(type=='ME')
		{
			target = rival;
			atker = '你';
			beatker = rival.name;
			hpBox='rival_hp';
			fightBox = 'rival';
		}else{
			target = myCharacter;
			atker = rival.name;
			beatker = '你';
			hpBox='my_hp';
			fightBox = 'my_character';
		}
		
		target.hp -= data.d;
		
		if(target.hp<=0) data.m='DIE';
		
		switch(data.m)
		{			
			case 'MISS':
				
				msg='<font color="#F2F68C">'+atker+'未命中</font><br>';
				break;
			
			case 'ATK':
				
				msg=atker+'对'+beatker+'攻击造成了'+data.d+'点伤害<br>';
				break;
			
			case 'CRI':
				
				msg='<font color="#FF9900">'+atker+'对'+beatker+'会心一击造成了<b>'+data.d+'</b>点伤害</font><br>';
				break;
			
			case 'DIE':	
				msg='<font color="#FF0000">'+atker+'把'+beatker+'杀死了</font><br>';
				break;
		}
		
		$('battle_history').innerHTML+=msg;
		$('battle_history').scrollTop = $('battle_history').scrollHeight;
		
		if(data.m!='DIE')
		{
			$(hpBox).innerHTML = target.hp;
			if(hpBox=='my_hp') myCharacter.setupUserinfo();
		}else{
			fightMonsterEnd();
		}
		
		
		fightMonsterChangeTurn();
	}
	
	function fightMonsterDef()
	{
	}
	
	function fightMonsterFight(atker,defer)
	{
		if(rival==null) return;
		var rand = Math.floor(Math.random()*20);
		var hurt = monsterFightBaseAtk(atker.lv,atker.str)+atker.atk; // 基本攻击+装备加成
		var msg = '';
		if(rand==19)
		{
			// 暴击
			msg='CRI';
		}else if(rand==1){
			// MISS
			hurt = 0;
			msg='MISS'
		}else{
			def = Math.floor(monsterFightBaseDef(defer.lv,defer.vit)+parseInt(defer.def));
			hurt = hurt-def;
			if(hurt<=0) hurt=1;
			msg='ATK';
		}
		
		if(hurt>10 && msg!='CRI')
		{
			hurt = Math.floor(hurt-hurt*0.8*((100*Math.random()+(atker.dex/150))/100));
		}
		
		return {m:msg,d:hurt};
	}
	
	// 根据双方等级计算谁先开始攻击
	function fightMonsterDefineTurn()
	{
		if(rival==null) return 'OPP';
		if(parseInt(myCharacter.lv)>parseInt(rival.lv)*2) return 'ME';
		if((parseInt(myCharacter.lv)+parseInt(myCharacter.agi)*2)>(parseInt(rival.lv)+parseInt(rival.agi)*2))
			return 'ME';
		else
			return 'OPP';
	}
	
	function fightMonsterChangeTurn()
	{
		monster_fight_Turn = monster_fight_Turn=='ME' ? 'OPP' : 'ME';
	}
	
	function fightMonsterEnd()
	{
		$(fightBox).style.display='none';
		
		if(fightBox=='rival')
		{
			// 怪物战死
			action = 'monsterFightEnd';
		}else{
			// 自己战死
			action = 'iAmDie';
		}
		
		var opp = rival;
		rival=null;
		new Ajax.Request(
			'd5power.php', {
			method: 'post',
			parameters: 'action='+action+'&rival='+opp.monsterId,
			onComplete: function(result) {
				var server_data = eval("(" + result.responseText + ")");
				$('battle_history').innerHTML='<font class=monster_fight_msg>'+server_data.msg+'</font>';
				//alert(server_data.item_id);

				$('battle_history').scrollTop = $('battle_history').scrollHeight;
				setTimeout("hiddenMonsterBattleScreen()",5000);
				if(server_data.goHome=='Y')
				{
					changeMapDo();
				}else{
					if(server_data.xp>0)
					{
						myCharacter.xp=parseInt(myCharacter.xp)+parseInt(server_data.xp);
					}
					if(server_data.lvup)
					{
						myCharacter.xp=0;
						myCharacter.lv=parseInt(myCharacter.lv)+1;
					}
					if(server_data.item_id>0)
					{
						try{
							target = $('itemNumber_'+server_data.item_id);
							if(target!=undefined)
							{
								target.innerHTML = parseInt(target.innerHTML)+1;
							}else{
								addNewItem(server_data.item_id);
							}
						}catch(e){
							addNewItem(server_data.item_id);
						}
					}
					myCharacter.setupUserinfo();
				}
			}});
		
	}
	
	function monsterFightBaseAtk(lv,str)
	{
		return (parseInt(lv)+Math.floor(str/5));
	}
	
	function monsterFightBaseDef(lv,vit)
	{
		return (parseInt(lv)+Math.floor(vit/5));
	}